import sys
import getopt

from urllib.request import urlopen
from page.link import Link
from page.document import Document
from page.downloader import Downloader


def _usage():
    print(
    """
网页下载器:
    -h,--help     帮助信息
    -t,--timeout  指定超时时间
    -e,--encoding 指定保存文件时使用的编码
    -p,--path     指定存储目录
    """)

try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], 'ht:e:p:', [
                                        'help','time=','encoding=','path='])
except getopt.GetoptError as err:
    print(err)
    _usage()
    sys.exit()

timeout = encoding = path = None 
for opt, value in opts:
    if opt in ['-h','--help']:
        _usage()
        sys.exit(0)
    if opt in ['-t','--timeout']:
        timeout = value
    if opt in ['-e','--encoding']:
        encoding = value 
    if opt in ['-p','--path']:
        path = value 

if len(args) < 1:
    print('[!! 未指定目标页面链接 ]')
    sys.exit(1)

dw = Downloader(timeout=timeout, encoding=encoding, path=path)
dw.download(args[0])